package cn.ecut.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Author ruanxin
 */

//动态的创造对象，通过反射
public class Test06 {
    public static void main(String[] args) throws Exception {
        //获得Class对象
        Class c1 = Class.forName("cn.ecut.reflection.User");

        //构造一个对象
//        User user = (User)c1.newInstance();//本质调用无参构造
//        System.out.println(user);

        //通过构造器创建对象
        //String name, int id, int age, int sb, String bir, double money
//        Constructor constructor = c1.getDeclaredConstructor(String.class,int.class,int.class,int.class,String.class,double.class);
//        User user = (User) constructor.newInstance("sb", 001, 002, 003, "20201014", 9.15);
//        System.out.println(user);

        //通过反射调用普通方法
        User user = (User)c1.newInstance();
        //通过反射获取一个方法
        Method testmethod = c1.getDeclaredMethod("testmethod", null);
        testmethod.setAccessible(true);//暴力反射
        testmethod.invoke(user);

        //通过反射操作属性
        System.out.println("==============================");
        User user2 = (User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        name.set(user2,"张三");
        System.out.println(user2.getName());

    }
}
